package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.OrderDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.ShopDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.ShopItemDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Order;
import edu.ynu.se.xiecheng.achitectureclass.entity.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

@Service
public class ShopService extends LogicService<ShopDao, Shop,Long> {
    public ShopService(@Qualifier("shopDao") @Autowired ShopDao dao) {
        super(dao);
    }
    @Autowired
    private ShopItemDao shopItemDao;

    public List<Order> getOrdersByShopItemId(Long shopItemId) {
        return shopItemDao.findOrdersByShopItemId(shopItemId);
    }

    @Autowired
    private OrderDao orderDao;

    public void confirmOrder(Long orderId) {    //确认订单
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        if (optionalOrder.isPresent()) {
            Order order = optionalOrder.get();
            if (order.isPaid() && !order.isCancelled()) {
                order.confirmOrder();
                orderDao.save(order);
            } else {
                throw new IllegalArgumentException("Unable to confirm the order");
            }
        } else {
            throw new NoSuchElementException("Order not found");
        }
    }
    public void refundOrder(Long orderId) { //取消支付并退款
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        if (optionalOrder.isPresent()) {
            Order order = optionalOrder.get();
            if (order.isPaid() && !order.isCancelled() && !order.isRefunded()) {
                order.refundOrder();
                orderDao.save(order);
            } else {
                throw new IllegalArgumentException("Unable to refund the order");
            }
        } else {
            throw new NoSuchElementException("Order not found");
        }
    }
}
